package com.easy.dfc.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.easy.core.web.BaseController;
import com.easy.dfc.Utils.JsonUtil;
import com.easy.dfc.Utils.PagingUtil;
import com.easy.dfc.Utils.Util;
import com.easy.dfc.Utils.Error;
import com.easy.dfc.entity.*;
import com.easy.dfc.service.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by VULCANTSeries on 2017/6/2.
 */
@Controller
@RequestMapping("${apiPath}/Order")
public class OrderController extends BaseController {

    @Resource
    private UsersetService usersetService;

    @Resource
    private OrderSetService orderSetService;

    @Resource
    private SkuSetService skuSetService;

    @Resource
    private FactorySetService factorySetService;

    @Resource
    private DealerSetService dealerSetService;

    @Resource
    private ProductsetService productsetService;

    @Resource
    private TiantiantejiaService tiantiantejiaService;

    @Resource
    private TiaoweihuosetService tiaoweihuosetService;

    @Resource
    private TuangouService tuangouService;

    @Resource
    private OrderActionService orderActionService;

    /**
     * 拍照上传，表示发货,并更改订单状态
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/Upload", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> Upload(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        JSONObject jsonObject = new JSONObject();
        try {
            String userId = request.getParameter("UserId");
            String token = request.getParameter("Token");
            if (!usersetService.VerifyToken(userId, token)) {
                jsonObject.put("Err", Error.ValidFailed);
                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
            }
            int OrderId = Integer.parseInt(request.getParameter("orderId"));
            OrderSetWithBLOBs orderSetWithBLOBs = orderSetService.selectById(OrderId);
            //订单要存在并且是已付款状态才可以
            if (orderSetWithBLOBs == null) {
                jsonObject.put("Err", Error.NotOrder);
                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
            } else if (orderSetWithBLOBs.getStatus() != OrderStutas.Paid) {
                jsonObject.put("Err", Error.OrderStutsErr);
                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
            }
            String path = Util.UploadImages(request, "orderimgs");
            if (path != null) {
                orderSetWithBLOBs.setDeliveryimg(path);
                orderSetWithBLOBs.setStatus(OrderStutas.Delivery);
                orderSetService.updateByPrimaryKeySelective(orderSetWithBLOBs);
                jsonObject.put("Err", Error.OK);
            } else {
                jsonObject.put("Err", Error.InputError);
                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
            }
            //添加订单行为记录
            Util.AddOrderAction(OrderId, orderActionService, OrderStutas.Delivery);
        } catch (IOException e) {
            jsonObject.put("Err", Error.UploadFaild);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * 买家确认收货
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/confirmGet", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> confirmGet(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        JSONObject jsonObject = new JSONObject();
        try {
            String userId = request.getParameter("UserId");
            String token = request.getParameter("Token");
            if (!usersetService.VerifyToken(userId, token)) {
                jsonObject.put("Err", Error.ValidFailed);
                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
            }
            int orderId = Integer.parseInt(request.getParameter("orderId"));
            Userset userset = orderSetService.selectUser(orderId);
            //判断该订单是不是该用户的
            if (!userId.equals(userset.getUserid().replaceAll("-", ""))) {
                jsonObject.put("Err", Error.OrderNotUser);
                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
            }
            OrderSetWithBLOBs orderSetWithBLOBs = orderSetService.selectById(orderId);
            orderSetWithBLOBs.setStatus(OrderStutas.TakeDelivery);
            orderSetService.updateByPrimaryKeySelective(orderSetWithBLOBs);
            Util.AddOrderAction(orderId, orderActionService, OrderStutas.TakeDelivery);
            jsonObject.put("Err", Error.OK);
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }

        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * 卖家取消订单
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/orderCancel", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> orderCancel(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        JSONObject jsonObject = new JSONObject();
        try {
            String userId = request.getParameter("UserId");
            String token = request.getParameter("Token");
            if (!usersetService.VerifyToken(userId, token)) {
                jsonObject.put("Err", Error.ValidFailed);
                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
            }
            int orderId = Integer.parseInt(request.getParameter("orderId"));
            Userset userset = orderSetService.selectUserByFactory(orderId);
            if (!userId.equals(userset.getUserid().replaceAll("-", ""))) {
                jsonObject.put("Err", Error.OrderNotUser);
                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
            }
            OrderSetWithBLOBs orderSetWithBLOBs = orderSetService.selectById(orderId);
            orderSetWithBLOBs.setStatus(OrderStutas.Cancel);
            //恢复库存
            List<OrderItemSetWithBLOBs> orderItemSetWithBLOBsList = orderSetService.selectByOrderSetId(orderId);
            for (OrderItemSetWithBLOBs o : orderItemSetWithBLOBsList) {
                SkuSet skuSet = skuSetService.selectByPrimaryKey(o.getSkuid());
                skuSet.setStock(skuSet.getStock() + o.getNum());
                skuSetService.updateByPrimaryKeySelective(skuSet);
            }
            orderSetService.updateByPrimaryKeySelective(orderSetWithBLOBs);
            //记录
            Util.AddOrderAction(orderId, orderActionService, OrderStutas.Cancel);
            jsonObject.put("Err", Error.OK);
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }

        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * 获取订单列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/OrderList", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> OrderList(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        JSONObject jsonObject = new JSONObject();
        try {
            String userId = request.getParameter("UserId");
            String token = request.getParameter("Token");
            if (!usersetService.VerifyToken(userId, token)) {
                jsonObject.put("Err", Error.ValidFailed);
                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
            }
            //要获取的订单状态,不传为获取全部状态的订单
            String stuts = request.getParameter("Stuts");
            int start = Integer.parseInt(request.getParameter("Page"));
            PagingUtil pagingUtil = new PagingUtil();
            //如果是null，则赋值为-1，查询全部
            pagingUtil.setBrandId(Integer.parseInt(stuts == null ? "-1" : stuts));
            pagingUtil.setStart((start - 1) * 20);
            pagingUtil.setUserId(Util.ToUuidString(userId));
            List<OrderSetWithBLOBs> orderSetWithBLOBsList = new ArrayList<>();
            //type为1表示卖家，2表示买家
            String type = request.getParameter("type");
            if ("1".equals(type)) {
                orderSetWithBLOBsList = orderSetService.selectByFactoryId(pagingUtil);
            } else if ("2".equals(type)) {
                orderSetWithBLOBsList = orderSetService.selectByDealerId(pagingUtil);
            }
            //遍历，获取子订单详情数组
            for (OrderSetWithBLOBs o : orderSetWithBLOBsList) {
                o.setOrderItemSetWithBLOBsList(orderSetService.selectByOrderSetId(o.getId()));
            }
            String str = JSONObject.toJSONString(orderSetWithBLOBsList);
            jsonObject = JSONObject.parseObject(JsonUtil.toErrJson(Error.OK, str));
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }

        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * 获取订单各状态数量
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/OrderStatusNum", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> OrderStatusNum(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        JSONObject jsonObject = new JSONObject();
        try {
            String userId = request.getParameter("UserId");
            String token = request.getParameter("Token");
            if (!usersetService.VerifyToken(userId, token)) {
                jsonObject.put("Err", Error.ValidFailed);
                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
            }
            List<OrderStatusNum> orderStatusNumList = new ArrayList<>();
            //type为1表示卖家，2表示买家
            String type = request.getParameter("type");
            if ("1".equals(type)) {
                orderStatusNumList = orderSetService.selectStatusNumByFactory(Util.ToUuidString(userId));
            } else if ("2".equals(type)) {
                orderStatusNumList = orderSetService.selectStatusNumByDealer(Util.ToUuidString(userId));
            }
            String str = JSONObject.toJSONString(orderStatusNumList);
            jsonObject = JSONObject.parseObject(JsonUtil.toErrJson(Error.OK, str));
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }

        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * 创建订单
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/OrderCreated", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> OrderCreated(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        JSONObject jsonObject = new JSONObject();
        try {
            String userId = request.getParameter("UserId");
            String token = request.getParameter("Token");
            if (!usersetService.VerifyToken(userId, token)) {
                jsonObject.put("Err", Error.ValidFailed);
                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
            }
            int DistributionInformationId = Integer.parseInt(request.getParameter("DistributionInformationId"));
            String OrderItemList = request.getParameter("OrderItemList");
            JSONArray jsonArray = JSONObject.parseArray(OrderItemList);
            //先获取订单编号，然后创建订单对象并存入数据库，再获得该订单Id，根据Id创建子订单对象并存入数据库,同时计算出总价
            String itemNo = Util.getOrderItemNo();
            OrderSetWithBLOBs orderSet = new OrderSetWithBLOBs();
            orderSet.setCreated(new Date());
            orderSet.setStatus(0);
            orderSet.setAmount(new BigDecimal(0));
            orderSet.setDistributionId(DistributionInformationId);
            orderSet.setItemno(itemNo);
            orderSet.setRemark(" ");
            orderSet.setDealerId(dealerSetService.selectDealerIdByUserId(Util.ToUuidString(userId)).getId());
            orderSet.setFactoryId(factorySetService.selectFactoryIdBySkuId(Integer.parseInt(JSONObject.parseObject(jsonArray.get(0).toString()).get("SkuId").toString())).getId());
            List<OrderItemSetWithBLOBs> orderItemSetWithBLOBsList = new ArrayList<>();
            List<SkuSet> skuSetList = new ArrayList<>();
            List<Enrolltuangou> enrolltuangouList = new ArrayList<>();
            //总价
            BigDecimal amount = new BigDecimal(0);
            int number = 0;
            for (Object object : jsonArray) {
                JSONObject json = JSONObject.parseObject(object.toString());
                OrderItemSetWithBLOBs orderItemSet = new OrderItemSetWithBLOBs();
                int skuId = Integer.parseInt(json.get("SkuId").toString());
                int num = Integer.parseInt(json.get("Num").toString());
                number += num;
                ProductsetWithBLOBs productsetWithBLOBs = productsetService.selectBySkuId(skuId);
                //判断是否在活动中
                if (Util.PromotionStuts(productsetWithBLOBs, tiantiantejiaService, tiaoweihuosetService, tuangouService)) {
                    //如果是在团购中，判断团购数量是否足够
                    if ("团购".equals(productsetWithBLOBs.getPromotiontype())) {
                        List<TuangouWithBLOBs> tuangouWithBLOBsList = tuangouService.getTuangou(productsetWithBLOBs.getProductid());
                        if (tuangouWithBLOBsList != null) {
                            long time = new Date().getTime() / 1000;
                            for (TuangouWithBLOBs t : tuangouWithBLOBsList) {
                                if (t.getStart() < time && t.getEnd() > time) {
                                    if (number + tuangouService.selectNumByTuangouId(t.getId()).getNum() > t.getMaxnum()) {
                                        jsonObject.put("Err", Error.TuangouOut);
                                        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
                                    } else {
                                        Enrolltuangou enrolltuangou = new Enrolltuangou();
                                        enrolltuangou.setNum(num);
                                        enrolltuangou.setUserid(Util.ToUuidString(userId));
                                        enrolltuangou.setSkuId(skuId);
                                        enrolltuangou.setTuangouid(t.getId());
                                        enrolltuangouList.add(enrolltuangou);
                                    }
                                }
                            }
                        }
                    }
                    amount = new BigDecimal(amount.doubleValue() + num * productsetWithBLOBs.getPromotionprice().doubleValue());
                    orderItemSet.setPrice(productsetWithBLOBs.getPromotionprice());
                    orderItemSet.setPromotionType(productsetWithBLOBs.getPromotiontype());
                } else {
                    orderItemSet.setPrice(productsetWithBLOBs.getPrice());
                    amount = new BigDecimal(amount.doubleValue() + num * productsetWithBLOBs.getPrice().doubleValue());
                }
                orderItemSet.setNum(num);
                orderItemSet.setSkuid(skuId);
                orderItemSet.setBrandId(productsetWithBLOBs.getBrandId());
                orderItemSet.setItemno(productsetWithBLOBs.getItemno());
                orderItemSet.setMainimg(productsetWithBLOBs.getMainimg());
                orderItemSet.setName(productsetWithBLOBs.getName());
                SkuSet skuSet = skuSetService.selectByPrimaryKey(skuId);
                if (skuSet.getStock() < num) {
                    jsonObject.put("Err", Error.OverStock);
                    return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
                }
                skuSet.setStock(skuSet.getStock() - num);
                orderItemSet.setSkuinfo(skuSet.getName());
                orderItemSet.setProductid(productsetWithBLOBs.getProductid());
                orderItemSetWithBLOBsList.add(orderItemSet);
                skuSetList.add(skuSet);
            }
            //数据库操作集中执行
            orderSetService.insertSelective(orderSet);
            for (int i = 0; i < orderItemSetWithBLOBsList.size(); i++) {
                orderItemSetWithBLOBsList.get(i).setOrderId(orderSet.getId());
                skuSetService.updateByPrimaryKeySelective(skuSetList.get(i));
                orderSetService.insertSelective(orderItemSetWithBLOBsList.get(i));
            }
            for (int i = 0; i < enrolltuangouList.size(); i++) {
                enrolltuangouList.get(i).setOrderid(orderSet.getId());
                tuangouService.insertSelective(enrolltuangouList.get(i));
            }
            orderSet.setAmount(amount);
            orderSetService.updateByPrimaryKeySelective(orderSet);
            List<String> OrderItemNoList = new ArrayList<>();
            OrderItemNoList.add(itemNo);
            //添加订单行为记录
            Util.AddOrderAction(orderSet.getId(), orderActionService, OrderStutas.Unpaid);
            jsonObject.put("Err", Error.OK);
            jsonObject.put("OrderItemNoList", OrderItemNoList);
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }

        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * 获取订单行为记录
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/OrderAction", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> OrderAction(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        JSONObject jsonObject = new JSONObject();
        try {
            String userId = request.getParameter("UserId");
            String token = request.getParameter("Token");
            if (!usersetService.VerifyToken(userId, token)) {
                jsonObject.put("Err", Error.ValidFailed);
                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
            }
            int orderId = Integer.parseInt(request.getParameter("orderId"));
            List<OrderAction> orderActionList = orderActionService.selectByOrderId(orderId);
            String str = JSONObject.toJSONString(orderActionList);
            jsonObject = JSONObject.parseObject(JsonUtil.toErrJson(Error.OK, str));
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }

        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }
}
